<template>
    <el-menu
      :default-active="activeMenu"
      mode="horizontal"
      @select="handleSelect"
      :ellipsis="false"
    >
      <template v-for="(item, index) in topMenus" :key="index">
        <el-menu-item
          :style="{'--theme': theme}"
          :index="item.path"
          v-if="index < visibleNumber"
        >
          <svg-icon :icon-class="item.meta?.icon" />
          {{ item.meta?.title }}
        </el-menu-item>
      </template>
  
      <!-- 顶部菜单超出数量折叠 -->
      <el-sub-menu
        :style="{'--theme': theme}"
        index="more"
        v-if="topMenus.length > visibleNumber"
      >
        <template #title>更多菜单</template>
        <template v-for="(item, index) in topMenus" :key="index">
          <el-menu-item
            :index="item.path"
            v-if="index >= visibleNumber"
          >
            <svg-icon :icon-class="item.meta?.icon" />
            {{ item.meta?.title }}
          </el-menu-item>
        </template>
      </el-sub-menu>
    </el-menu>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { constantRoutes } from "@/router";
  import { isHttp } from '@/utils/validate';
  import { useAppStore } from '@/store/modules/app';
  import { useSettingsStore } from '@/store/modules/settings';
  import { usePermissionStore } from '@/store/modules/permission';
  
  /**
   * 顶部栏初始数
   */
  const visibleNumber = ref<number>(0);
  
  /**
   * 当前激活菜单的 index
   */
  const currentIndex = ref<string | null>(null);
  
  /**
   * 隐藏侧边栏路由
   */
  const hideList: string[] = ['/index', '/user/profile'];
  
  /**
   * 应用程序状态
   */
  const appStore = useAppStore();
  
  /**
   * 设置状态
   */
  const settingsStore = useSettingsStore();
  
  /**
   * 权限状态
   */
  const permissionStore = usePermissionStore();
  
  /**
   * 当前路由
   */
  const route = useRoute();
  
  /**
   * 路由器实例
   */
  const router = useRouter();
  
  /**
   * 主题颜色
   * @returns 返回当前主题颜色
   */
  const theme = computed(() => settingsStore.theme);
  
  /**
   * 所有的路由信息
   * @returns 返回所有顶级路由
   */
  const routers = computed(() => permissionStore.topbarRouters);
  
  /**
   * 顶部显示菜单
   * @returns 返回过滤后的顶部菜单
   */
  const topMenus = computed(() => {
    return routers.value.filter(menu => !menu.hidden).map(menu => 
      menu.path === '/' ? (menu.children ? menu.children[0] : menu) : menu
    );
  });
  
  /**
   * 设置子路由
   * @returns 返回合并后的子路由
   */
  const childrenMenus = computed(() => {
    const menus: any[] = [];
    routers.value.forEach(router => {
      Object.values(router.children || {}).forEach(item => {
        if (item.parentPath === undefined) {
          if (router.path === '/') {
            item.path = `/${item.path}`;
          } else if (!isHttp(item.path)) {
            item.path = `${router.path}/${item.path}`;
          }
          item.parentPath = router.path;
        }
        menus.push(item);
      });
    });
    return constantRoutes.concat(menus);
  });
  
  /**
   * 默认激活的菜单
   * @returns 返回默认激活的菜单路径
   */
  /**
 * 默认激活的菜单
 * @returns 返回默认激活的菜单路径
 */
const activeMenu = computed(() => {
  const path = route.path;
  let activePath = path;

  // 检查路径中是否包含斜杠，并且不在隐藏列表中
  if (path && path.lastIndexOf('/') > 0 && !hideList.includes(path)) {
    const tmpPath = path.substring(1, path.length);
    activePath = '/' + tmpPath.substring(0, tmpPath.indexOf('/'));
    // 如果当前路由没有 link 元数据，则显示侧边栏
    if (!route.meta.link) {
      appStore.toggleSideBarHide(false);
    }
  } else {
    // 如果路径没有斜杠或者在隐藏列表中
    activePath = path;
    // 检查当前路由是否有子路由
    const hasChildren = route.matched.some(record => record.children && record.children.length > 0);
    if (!hasChildren) {
      appStore.toggleSideBarHide(true);
    }
  }

  // 激活相关联的路由
  activeRoutes(activePath);
  return activePath;
});
  
  /**
   * 根据窗口宽度设置可见菜单数量
   */
  function setVisibleNumber() {
    const width = document.body.getBoundingClientRect().width / 3;
    visibleNumber.value = Math.floor(width / 85);
  }
  
  /**
   * 处理菜单选择事件
   * @param key - 选中的菜单项键
   * @param keyPath - 选中的菜单项路径
   */
  function handleSelect(key: string, keyPath: string[]) {
    currentIndex.value = key;
    const route = routers.value.find(item => item.path === key);
    if (isHttp(key)) {
      window.open(key, '_blank');
    } else if (!route || !route.children) {
      const routeMenu = childrenMenus.value.find(item => item.path === key);
      if (routeMenu && routeMenu.query) {
        const query = JSON.parse(routeMenu.query);
        router.push({ path: key, query });
      } else {
        router.push({ path: key });
      }
      appStore.toggleSideBarHide(true);
    } else {
      activeRoutes(key);
      appStore.toggleSideBarHide(false);
    }
  }
  
  /**
   * 激活相关联的路由
   * @param key - 激活的路由键
   * @returns 返回相关的子路由
   */
  function activeRoutes(key: string): void {
    const routes = childrenMenus.value.filter(item => key === item.parentPath || (key === 'index' && item.path === '')).map(item => item);
    if (routes.length > 0) {
      permissionStore.setSidebarRouters(routes);
    } else {
      appStore.toggleSideBarHide(true);
    }
  }
  
  // 监听窗口大小变化，更新可见菜单数量
  onMounted(() => {
    window.addEventListener('resize', setVisibleNumber);
    setVisibleNumber();
  });
  onBeforeUnmount(() => {
    window.removeEventListener('resize', setVisibleNumber);
  });
  </script>
  
  <style lang="scss" scoped>
  .topmenu-container.el-menu--horizontal > .el-menu-item,
  .topmenu-container.el-menu--horizontal > .el-sub-menu .el-sub-menu__title {
    float: left;
    height: 50px !important;
    line-height: 50px !important;
    color: #999093 !important;
    padding: 0 5px !important;
    margin: 0 10px !important;
  }
  
  .topmenu-container.el-menu--horizontal > .el-menu-item.is-active,
  .topmenu-container.el-menu--horizontal > .el-sub-menu.is-active .el-submenu__title {
    border-bottom: 2px solid var(--theme) !important;
    color: #303133;
  }
  </style>